package com.ruoyi.project.zxcrm.controller;


import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.zx.PageData;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.framework.config.RuoYiConfig;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.project.system.domain.SysDictData;
import com.ruoyi.project.system.mapper.SysDictDataMapper;
import com.ruoyi.project.zxbd.service.impl.BdPartnerServiceImpl;
import com.ruoyi.project.zxcrm.domain.CrmResume;
import com.ruoyi.project.zxcrm.enums.ResumeSourcesEnum;
import com.ruoyi.project.zxcrm.mapper.CrmResumeMapper;
import com.ruoyi.project.zxcrm.service.ICrmResumeService;
import com.ruoyi.project.zxcrm.service.impl.CrmLeadServiceImpl;
import com.ruoyi.project.zxcrm.service.impl.CrmResumeServiceImpl;
import com.ruoyi.project.zxcrm.utils.ResumeUtil;
import com.ruoyi.project.zxcrm.utils.verifyPhone;
import lombok.AllArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;

/**
 * 简历信息Controller
 *
 * @author mn
 * @date 2022-05-13
 */
@Transactional(rollbackFor = Exception.class)
@RestController
@RequestMapping("/crm/resume")
@AllArgsConstructor
public class CrmResumeController extends BaseController {
    private CrmResumeServiceImpl crmResumeService;

    private BdPartnerServiceImpl BdPartnerService;

    private CrmLeadServiceImpl CrmLeadService;

    private CrmResumeMapper crmResumeMapper;

    private SysDictDataMapper sysDictDataMapper;

    /**
     * 查询简历信息列表
     */
    @PreAuthorize("@ss.hasPermi('crm:resume:list')")
    @GetMapping("/list")
    public TableDataInfo list(CrmResume crmResume, @RequestParam(value = "sales", required = false) Long sales) {
        startPage();
        if (sales != null && !"".equals(sales)) {
            crmResume.setUserId(sales);
        } else if ("".equals(crmResume.getUserId()) || crmResume.getUserId() == null) {
            crmResume.setUserId(this.getUserId());
        }
        startPage();
        List<CrmResume> list = crmResumeService.selectCrmResumeList(crmResume);
        return getDataTable(list);
    }

    /**
     * 导出简历信息列表
     */
    @PreAuthorize("@ss.hasPermi('crm:resume:export')")
    @Log(title = "简历信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, CrmResume crmResume) throws Exception {
        List<CrmResume> list = crmResumeService.selectCrmResumeList(crmResume);
        ExcelUtil<CrmResume> util = new ExcelUtil<CrmResume>(CrmResume.class);
        util.exportExcel(response, list, "简历信息数据");
    }

    /**
     * 获取简历信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('crm:resume:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        CrmResume crmResume = crmResumeService.selectCrmResumeById(id);
        System.out.println(crmResume);
        return AjaxResult.success(crmResume);
    }

    /**
     * 获取简历信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('crm:resume:query')")
    @GetMapping(value = "/one")
    public AjaxResult getOne(CrmResume crmResume) {

        List<CrmResume> list = crmResumeService.selectCrmResumeList(crmResume);
        if (list.size() > 0) {
            CrmResume crmResume1 = list.get(0);
            return AjaxResult.success(crmResume1);
        } else {
            return AjaxResult.error("未查找到简历信息！");
        }
    }

    /**
     * 新增简历信息
     */
    @PreAuthorize("@ss.hasPermi('crm:resume:add')")
    @Log(title = "简历信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody CrmResume crmResume) {
        if (StringUtils.isEmpty(crmResume.getMobile())) {
            return AjaxResult.error("手机号不能为空");
        }
        CrmResume crmResume1 = crmResumeService.checkResumePhone(crmResume);
        if (crmResume1 != null) {
            return AjaxResult.error("手机号已存在");
        }
        return toAjax(crmResumeService.insertCrmResume(crmResume));
    }

    /**
     * 修改简历信息
     */
    @PreAuthorize("@ss.hasPermi('crm:resume:edit')")
    @Log(title = "简历信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody CrmResume crmResume, boolean updateSupport, boolean check2) {

        if (updateSupport) {
            crmResume.setParams("is_partner_update", "0");
        } else {
            crmResume.setParams("is_partner_update", "1");
        }
        if (check2) {
            crmResume.setParams("is_lead_update", "0");
        } else {
            crmResume.setParams("is_lead_update", "1");
        }
        return toAjax(crmResumeService.updateCrmResume(crmResume));
    }

    /**
     * 删除简历信息
     */
    @PreAuthorize("@ss.hasPermi('crm:resume:remove')")
    @Log(title = "简历信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(crmResumeService.deleteCrmResumeByIds(ids));
    }

    @PostMapping("/upload")
    public AjaxResult uploadFile(MultipartFile fileObj, boolean updateSupport, boolean updateLead) throws Exception {
        CrmResume resume = null;
        PageData pd = new PageData();
        if (fileObj.isEmpty()) {
            logger.warn("文件不能为空");
            return AjaxResult.error("文件不能为空");
        }
        pd.put("originalFilename", fileObj.getOriginalFilename());
//        String originalFilename = fileObj.getOriginalFilename();
        logger.info("originalFilename:" + pd.getString("originalFilename"));
        if (StringUtils.isEmpty(pd.getString("originalFilename"))) {
            logger.warn("文件名称不能为空");
            return AjaxResult.error("文件名称不能为空");
        }
        byte[] buffer;
        buffer = ResumeUtil.getInputStream(fileObj);
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(buffer);
        InputStream inputStream = fileObj.getInputStream();
        String jsonStr = null;
        if (pd.getString("originalFilename").contains("51job")) {
            jsonStr = ResumeUtil.get51(inputStream);
        } else if (pd.getString("originalFilename").contains("新安人才网")) {
            jsonStr = ResumeUtil.getXinAnRenCai(byteArrayInputStream);
        } else if (pd.getString("originalFilename").contains("58简历")) {
            jsonStr = ResumeUtil.get58(byteArrayInputStream);
        } else if (pd.getString("originalFilename").contains("智联")) {
            jsonStr = ResumeUtil.getZhiLian(byteArrayInputStream);
        } else if (pd.getString("originalFilename").contains("Boss直聘")) {
            jsonStr = ResumeUtil.getBossZhiPin(byteArrayInputStream);
        } else {
            jsonStr = ResumeUtil.getBossZhiPin(byteArrayInputStream);
        }
        resume = JSONObject.parseObject(jsonStr, CrmResume.class);

        synchronized (CrmResumeController.class) {
            // resume.setFile(buffer);
            String filePath = RuoYiConfig.getUploadPath();
            logger.info("路径" + filePath);
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, fileObj);
            resume.setFileName(fileName);
            // String url = serverConfig.getUrl() + fileName;
            resume.setUpdateBy(this.getUsername());
//            crmResumeService.insertCrmResume(resume);
            AjaxResult ajax = AjaxResult.success();
            // ajax.put("url", url);
            // resume.setFile(null);
            ajax.put("resume", JSONObject.parse(JSONObject.toJSONString(resume)));

            //手机号如果是空的，直接存数据库里，并且返回了。等人事手动识别 2023年5月26日, PM 10:10:03
            if (resume.getMobile() == null) {
                crmResumeService.insertCrmResume(resume);
                return AjaxResult.error("文件未自动识别到手机号：" + pd.getString("originalFilename"));
            }
            //检查手机号是否存在过数据，插入或者更新 2023年5月26日, PM 10:10:07
            CrmResume exiteCrmResume = crmResumeService.checkResumePhone(resume);
            if (updateSupport) {
                resume.setParams("is_partner_update", "0");
            } else {
                resume.setParams("is_partner_update", "1");
            }
            if (updateLead) {
                resume.setParams("is_lead_update", "0");
            } else {
                resume.setParams("is_lead_update", "1");
            }

            if (exiteCrmResume == null) {
                crmResumeService.insertCrmResume(resume);
            } else {
                resume.setId(exiteCrmResume.getId());
                resume.setRemark(resume.getRemark() + ",\n" + DateUtils.getDate() + ",再次投递,");
                crmResumeService.updateCrmResume(resume);
            }

            return ajax;
        }
    }

    @GetMapping("/nullPhone")
    public AjaxResult GetNullPhones() {
        return AjaxResult.success(crmResumeMapper.checkResumeNullMobile());
    }
}
